package server

import (
	"fmt"
	"my-gameserver-go/core/mynet"
	"my-gameserver-go/core/mynet/conn"
	"my-gameserver-go/logic/sample"
	"my-gameserver-go/logic/scene"
	"net"
)

type GameServer struct {
	Name      string
	IP        string
	Port      int
	IPVersion string
}

//NewGameServer 构造函数
func NewGameServer() *GameServer {
	s := &GameServer{
		Name:      "goServer",
		IPVersion: "tcp4",
		IP:        "127.0.0.1",
		Port:      6688,
	}
	return s
}

func (g *GameServer) Start() {
	fmt.Printf("[START] Server name: %s,listenner at IP: %s, Port %d is starting\n", g.Name, g.IP, g.Port)
	go func() {
		//启动sceneManager
		scene.InsManager.Start()
		//加载sample配置文件
		sample.InsSampleManager.Start()
		//启动netManager
		mynet.InsNetManager.Start()
		//启动connector
		g.StartConn()

	}()
	//阻塞,否则主Go退出， listenner的go将会退出
	select {}
}

func (g GameServer) StartConn() {
	//获取tcp的addr
	addr, err := net.ResolveTCPAddr(g.IPVersion, fmt.Sprintf("%s:%d", g.IP, g.Port))
	if err != nil {
		fmt.Println("resolve tcp addr err:", err)
	}
	//监听服务器地址
	listener, err := net.ListenTCP(g.IPVersion, addr)
	if err != nil {
		panic(err)
	}
	fmt.Println("start server success,servername:", g.Name)
	//无限循环,等待有连接建立
	for {
		//3.1 阻塞等待客户端建立连接请求
		tcpConn, err := listener.AcceptTCP()
		if err != nil {
			fmt.Println("Accept err ", err)
			continue
		}
		//有连接建立
		fmt.Println("Get conn remote addr = ", tcpConn.RemoteAddr().String())
		//3.2 设置服务器最大连接控制,如果超过最大连接，那么则关闭此新的连接
		//if s.ConnMgr.Len() >= global.MaxConn {
		//	conn.Close()
		//	continue
		//}
		dealConn := conn.CreateConnection(tcpConn)
		//3.4 启动当前链接的处理业务
		go mynet.InsNetManager.StartConn(dealConn)
	}

}

func (g GameServer) Stop() {
	//TODO implement me
	panic("implement me")
}

//-----------函数区
